<template>
  <div style="height: 100vh; position: relative">
    <!-- 水印层 -->
    <el-watermark
      v-if="showWatermark"
      :content="watermarkConfig.content"
      :font-size="watermarkConfig.fontSize"
      :font-color="watermarkConfig.color"
      :rotate="watermarkConfig.rotate"
      :gap="watermarkConfig.gap"
      :offset="watermarkConfig.offset"
      :z-index="1000"
      style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none"
    />

    <!-- 自适应模式下直接渲染，非自适应模式使用滚动条 -->
    <template v-if="canvas_cfg.adaptive_screen?.enabled">
      <div class="w-1/1 h-1/1 overflow-hidden" style="position: relative">
        <div
          ref="canvasAreaRef"
          :class="`canvasArea ${mtPreviewProps.canDrag ? 'cursor-grab' : ''} `"
          @mousedown="onMouseDown"
          @wheel="onMouseWheel"
        >
          <render-core
            v-model:done-json="done_json"
            :canvas-cfg="canvas_cfg"
            :grid-cfg="grid_cfg"
            :show-ghost-dom="false"
            :canvas-dom="canvasAreaRef"
            :global-lock="false"
            :preivew-mode="true"
            :show-popover="mtPreviewProps.showPopover"
          ></render-core>
        </div>
      </div>
    </template>

    <!-- 非自适应模式使用原有的滚动条逻辑 -->
    <template v-else>
      <el-scrollbar ref="elScrollbarRef" class="w-1/1 h-1/1" @scroll="onScroll">
        <div
          ref="canvasAreaRef"
          :class="`canvasArea ${mtPreviewProps.canDrag ? 'cursor-grab' : ''} `"
          @mousedown="onMouseDown"
          @wheel="onMouseWheel"
        >
          <render-core
            v-model:done-json="done_json"
            :canvas-cfg="canvas_cfg"
            :grid-cfg="grid_cfg"
            :show-ghost-dom="false"
            :canvas-dom="canvasAreaRef"
            :global-lock="false"
            :preivew-mode="true"
            :show-popover="mtPreviewProps.showPopover"
          ></render-core>
        </div>
        <drag-canvas
          ref="dragCanvasRef"
          :scale-ratio="canvas_cfg.scale"
          @drag-canvas-mouse-down="dragCanvasMouseDown"
          @drag-canvas-mouse-move="dragCanvasMouseMove"
          @drag-canvas-mouse-up="dragCanvasMouseUp"
        ></drag-canvas>
      </el-scrollbar>
    </template>

    <!-- 调试模式下的浮动按钮 -->
    <div v-if="debugModeStore.isDebugMode" class="debug-floating-buttons">
      <el-button
        circle
        size="small"
        type="primary"
        @click="openPerformancePanel"
        title="性能监控"
        class="debug-btn"
      >
        <span class="debug-icon">🚀</span>
      </el-button>
      <el-button
        circle
        size="small"
        type="success"
        @click="openWebSocketMonitor"
        title="WebSocket连接池监控"
        class="debug-btn"
      >
        <span class="debug-icon">🌐</span>
      </el-button>
    </div>

    <!-- 性能监控面板 -->
    <PerformanceMonitorPanel v-model="showPerformancePanel" />

    <!-- WebSocket连接池监控面板 -->
    <WebSocketPoolMonitor v-model="showWebSocketMonitor" />
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, computed, onUnmounted } from 'vue';
import RenderCore from '@/components/mt-edit/components/render-core/index.vue';
import type { IExportJson } from '../mt-edit/components/types';
import { useExportJsonToDoneJson } from '../mt-edit/composables';
import type { IDoneJson } from '../mt-edit/store/types';
import { getItemAttr, previewCompareVal, setItemAttr } from '../mt-edit/utils';
import { ElScrollbar, ElMessage, ElMessageBox, ElWatermark, ElButton } from 'element-plus';
import DragCanvas from '@/components/mt-edit/components/drag-canvas/index.vue';
import { wsManager } from '@/services/websocket';
import { useRealtimeDataStore } from '@/stores/realtime-data';
import { useDebugModeStore } from '@/stores/debug-mode';
import PerformanceMonitorPanel from '@/components/mt-edit/components/performance-monitor-panel/index.vue';
import WebSocketPoolMonitor from '@/components/mt-edit/components/websocket-pool-monitor/index.vue';
type MtPreviewProps = {
  exportJson?: IExportJson;
  canZoom?: boolean;
  canDrag?: boolean;
  showPopover?: boolean;
};
const mtPreviewProps = withDefaults(defineProps<MtPreviewProps>(), {
  canDrag: true,
  canZoom: true,
  showPopover: false
});
const emits = defineEmits(['onEventCallBack']);
const canvasAreaRef = ref();
const canvas_cfg = ref({
  width: 1920,
  height: 1080,
  scale: 1,
  color: '',
  img: '',
  guide: true,
  adsorp: true,
  adsorp_diff: 3,
  transform_origin: {
    x: 0,
    y: 0
  },
  drag_offset: {
    x: 0,
    y: 0
  },
  access_password: {
    hash: '',
    salt: ''
  },
  watermark: {
    enabled: false,
    content: '',
    fontSize: 16,
    color: 'rgba(0,0,0,0.15)',
    opacity: 0.15,
    rotate: -22,
    gap: [100, 100] as [number, number],
    offset: [0, 0] as [number, number]
  },
  dataSources: [],
  adaptive_screen: {
    enabled: false,
    mode: 'fit' as 'fit' | 'fill',
    auto_resize: false
  }
});

// 水印显示控制
const showWatermark = computed(() => {
  return canvas_cfg.value.watermark?.content && canvas_cfg.value.watermark.content.trim() !== '';
});

// 水印配置
const watermarkConfig = computed(() => {
  const config = canvas_cfg.value.watermark;
  return {
    content: config?.content || '',
    fontSize: config?.fontSize || 16,
    color: config?.color || 'rgba(0,0,0,0.15)',
    rotate: config?.rotate || -22,
    gap: config?.gap || [100, 100],
    offset: config?.offset || [0, 0]
  };
});
const grid_cfg = ref({
  enabled: true,
  align: true,
  size: 10
});
const done_json = ref<IDoneJson[]>([]);
const elScrollbarRef = ref<InstanceType<typeof ElScrollbar>>();
const dragCanvasRef = ref<InstanceType<typeof DragCanvas>>();

// 调试模式相关
const debugModeStore = useDebugModeStore();
const showPerformancePanel = ref(false);
const showWebSocketMonitor = ref(false);

const openPerformancePanel = () => {
  showPerformancePanel.value = true;
};

const openWebSocketMonitor = () => {
  showWebSocketMonitor.value = true;
};
const scroll_info = reactive({
  begin_left: 0,
  begin_top: 0,
  left: 0,
  top: 0
});
const onScroll = ({ scrollLeft, scrollTop }: { scrollLeft: number; scrollTop: number }) => {
  scroll_info.left = scrollLeft;
  scroll_info.top = scrollTop;
};
const onMouseDown = (e: MouseEvent) => {
  if (mtPreviewProps.canDrag) {
    dragCanvasRef.value?.onMouseDown(e);
  }
};
const dragCanvasMouseDown = () => {
  scroll_info.begin_left = scroll_info.left;
  scroll_info.begin_top = scroll_info.top;
};
const dragCanvasMouseMove = (move_x: number, move_y: number) => {
  let new_left = scroll_info.begin_left - move_x;
  let new_top = scroll_info.begin_top - move_y;
  elScrollbarRef.value?.setScrollLeft(new_left);
  elScrollbarRef.value?.setScrollTop(new_top);
};
/**
 * 画布拖动结束事件
 */
const dragCanvasMouseUp = () => {};
const setItemAttrByID = (id: string, key: string, val: any) => {
  return setItemAttr(id, key, val, done_json.value);
};
const setItemAttrs = (info: { id: string; key: string; val: any }[]) => {
  info.forEach((f) => {
    setItemAttr(f.id, f.key, f.val, done_json.value);
  });
};
const getItemAttrByID = (id: string, key: string, val: any) => {
  return getItemAttr(id, key, done_json.value);
};
const onMouseWheel = (e: any) => {
  if (e.ctrlKey && mtPreviewProps.canZoom) {
    e.preventDefault();
    e.stopPropagation();
    if (e.deltaY > 0) {
      canvas_cfg.value.scale = (canvas_cfg.value.scale * 10 - 1) / 10;
    } else if (e.deltaY < 0) {
      canvas_cfg.value.scale = (canvas_cfg.value.scale * 10 + 1) / 10;
    }
  }
};

// 预览页面自适应屏幕功能
const calculatePreviewAdaptive = () => {
  if (!canvas_cfg.value.adaptive_screen?.enabled) {
    // 禁用自适应时，恢复默认设置
    canvas_cfg.value.drag_offset = { x: 0, y: 0 };
    canvas_cfg.value.transform_origin = { x: 0, y: 0 };
    return;
  }

  // 获取预览容器尺寸（整个视口）
  const containerWidth = window.innerWidth;
  const containerHeight = window.innerHeight;
  const mode = canvas_cfg.value.adaptive_screen.mode;

  if (mode === 'fit') {
    // 按比例缩放逻辑 - 保持宽高比，适应容器，无滚动条
    const originalWidth = canvas_cfg.value.width;
    const originalHeight = canvas_cfg.value.height;

    // 计算缩放比例，确保画布完全适应容器
    const scaleX = containerWidth / originalWidth;
    const scaleY = containerHeight / originalHeight;
    const finalScale = Math.min(scaleX, scaleY, 2); // 最大缩放不超过2倍

    // 应用缩放
    canvas_cfg.value.scale = Math.max(finalScale, 0.1); // 最小缩放0.1倍

    // 计算缩放后的尺寸
    const scaledWidth = originalWidth * canvas_cfg.value.scale;
    const scaledHeight = originalHeight * canvas_cfg.value.scale;

    // 居中显示，消除滚动条
    canvas_cfg.value.drag_offset = {
      x: Math.max(0, (containerWidth - scaledWidth) / 2),
      y: Math.max(0, (containerHeight - scaledHeight) / 2)
    };
  } else if (mode === 'fill') {
    // 拉伸适应逻辑 - 改变画布尺寸填满整个容器，并调整所有组件
    if (!originalCanvasConfig || !originalDoneJson) {
      console.warn('⚠️ Original config not available for fill mode');
      return;
    }

    const originalWidth = originalCanvasConfig.width;
    const originalHeight = originalCanvasConfig.height;

    // 计算缩放比例 - 基于原始尺寸
    const scaleX = containerWidth / originalWidth;
    const scaleY = containerHeight / originalHeight;

    // 更新画布尺寸
    canvas_cfg.value.width = containerWidth;
    canvas_cfg.value.height = containerHeight;
    canvas_cfg.value.scale = 1;
    canvas_cfg.value.drag_offset = { x: 0, y: 0 };

    // 基于原始配置调整所有组件的位置和尺寸
    done_json.value = originalDoneJson.map((originalItem) => {
      const item = JSON.parse(JSON.stringify(originalItem));

      // 调整位置和尺寸
      item.binfo.left = originalItem.binfo.left * scaleX;
      item.binfo.top = originalItem.binfo.top * scaleY;
      item.binfo.width = originalItem.binfo.width * scaleX;
      item.binfo.height = originalItem.binfo.height * scaleY;

      return item;
    });
  }

  // 设置缩放原点为左上角
  canvas_cfg.value.transform_origin = { x: 0, y: 0 };
};

// 预览页面窗口resize监听
const onPreviewWindowResize = () => {
  if (canvas_cfg.value.adaptive_screen?.enabled) {
    // 延迟执行，避免频繁触发
    clearTimeout(previewResizeTimer);
    previewResizeTimer = setTimeout(() => {
      calculatePreviewAdaptive();
    }, 150);
  }
};

let previewResizeTimer: NodeJS.Timeout;
const setItemAttrByIDAsync = (id: string, key: string, val: any) => {
  // 通过改变属性的事件去设置值时 需要转换成宏任务 不然多个事件判断会有问题
  setTimeout(() => {
    setItemAttrByID(id, key, val);
  }, 0);
};
(window as any).$mtElMessage = ElMessage;
(window as any).$mtElMessageBox = ElMessageBox;
(window as any).$setItemAttrByID = (id: string, key: string, val: any) =>
  setItemAttrByIDAsync(id, key, val);
(window as any).$getItemAttrByID = getItemAttrByID;
(window as any).$previewCompareVal = previewCompareVal;
(window as any).$mtEventCallBack = (type: string, item_id: string, ...args: any[]) =>
  emits('onEventCallBack', type, item_id, ...args);

// 为组态组件提供实时数据访问方法
(window as any).$getRealtimeData = (pointId: string) => {
  return realtimeStore.getDataValue(pointId);
};
(window as any).$getRealtimeDataPoint = (pointId: string) => {
  return realtimeStore.getDataPoint(pointId);
};
(window as any).$getHistoryData = (pointId: string) => {
  return realtimeStore.getHistoryData(pointId);
};
(window as any).$subscribeData = (pointId: string, subscriberId: string) => {
  return realtimeStore.subscribe(pointId, subscriberId);
};
(window as any).$unsubscribeData = (pointId: string, subscriberId: string) => {
  return realtimeStore.unsubscribe(pointId, subscriberId);
};

// 临时调试函数 - 用于测试数据绑定
(window as any).$testDataBinding = (dataPointId: string = 'test_switch', value: any = true) => {
  const message = {
    type: 'data',
    data: { [dataPointId]: value },
    source: 'test_source',
    timestamp: Date.now()
  };
  realtimeStore.handleWebSocketMessage(message);
  console.log(`发送测试数据: ${dataPointId} = ${value}`);

  // 显示当前数据点状态
  setTimeout(() => {
    const dataPoint = realtimeStore.getDataPoint(dataPointId);
    console.log(`数据点 ${dataPointId} 状态:`, dataPoint);
  }, 100);
};

// 测试Switch组件的具体数据点
(window as any).$testSwitchData = (value: any = 1) => {
  const switchDataPointId = 'data.自动上袋.取袋.value';
  console.log(`测试Switch数据点: ${switchDataPointId} = ${value}`);

  const message = {
    type: 'data',
    data: {
      自动上袋: {
        取袋: {
          value: value
        }
      }
    },
    source: 'switch_test',
    timestamp: Date.now()
  };

  realtimeStore.handleWebSocketMessage(message);

  setTimeout(() => {
    const dataPoint = realtimeStore.getDataPoint(switchDataPointId);
    console.log(`Switch数据点状态:`, dataPoint);

    // 测试路径解析
    const pathResult = realtimeStore.getValueByPathId?.(switchDataPointId);
    console.log(`路径解析结果:`, pathResult);
  }, 100);
};

// 直接测试路径解析功能
(window as any).$testPathParsing = () => {
  console.log('=== 测试路径解析功能 ===');

  // 模拟数据
  const testData = {
    自动上袋: {
      取袋: {
        value: 1
      },
      拖袋: {
        value: 0
      }
    },
    实时: {
      产能: 58,
      合格率: 95.5
    }
  };

  // 测试不同路径
  const testPaths = [
    'data.自动上袋.取袋.value',
    'data.自动上袋.拖袋.value',
    'data.实时.产能',
    'data.实时.合格率',
    '自动上袋.取袋.value',
    '实时.产能'
  ];

  testPaths.forEach((path) => {
    const result = realtimeStore.extractValueByPath?.(testData, path);
    console.log(`路径 "${path}": ${result}`);
  });
};

// 检查当前组件的数据绑定配置
(window as any).$checkBindingConfig = () => {
  console.log('=== 当前组件数据绑定配置 ===');
  console.log('总组件数量:', done_json.value.length);

  done_json.value.forEach((comp, index) => {
    console.log(`组件 ${index + 1}:`, {
      id: comp.id,
      type: comp.type,
      tag: comp.tag,
      dataBinding: comp.data_binding,
      hasDataBinding: !!comp.data_binding,
      bindingEnabled: comp.data_binding?.enabled
    });
  });

  const bindingComponents = done_json.value.filter((item) => item.data_binding?.enabled);
  console.log('已启用数据绑定的组件数量:', bindingComponents.length);

  // 检查switch组件
  const switchComponents = done_json.value.filter((item) => item.tag === 'el-switch-vue');
  console.log('Switch组件数量:', switchComponents.length);
  switchComponents.forEach((comp, index) => {
    console.log(`Switch组件 ${index + 1}:`, {
      id: comp.id,
      dataBinding: comp.data_binding,
      props: comp.props
    });
  });
};

// 强制触发switch组件重新渲染
(window as any).$forceSwitchRefresh = () => {
  console.log('=== 强制刷新Switch组件 ===');
  const switchComponents = done_json.value.filter((item) => item.tag === 'el-switch-vue');
  switchComponents.forEach((comp) => {
    console.log('刷新Switch组件:', comp.id);
    // 强制更新组件
    comp.active = !comp.active;
    setTimeout(() => {
      comp.active = !comp.active;
    }, 100);
  });
};

// 检查Switch组件的数据点状态
(window as any).$checkSwitchDataPoint = () => {
  console.log('=== 检查Switch组件数据点状态 ===');
  const switchComponents = done_json.value.filter((item) => item.tag === 'el-switch-vue');

  switchComponents.forEach((comp, index) => {
    const dataPointId = comp.data_binding?.dataPointId;
    console.log(`Switch组件 ${index + 1} (${comp.id}):`);
    console.log('  数据点ID:', dataPointId);

    if (dataPointId) {
      const dataPoint = realtimeStore.getDataPoint(dataPointId);
      console.log('  数据点存在:', !!dataPoint);
      console.log('  数据点值:', dataPoint?.value);
      console.log('  数据点详情:', dataPoint);

      // 检查路径解析
      const pathResult = realtimeStore.getValueByPathId?.(dataPointId);
      console.log('  路径解析结果:', pathResult);

      // 检查所有数据点中是否有类似的
      const allDataPoints = realtimeStore.dataPoints.value || [];
      const similarPoints = allDataPoints.filter(
        (dp) =>
          dp.id.includes('自动上袋') || dp.id.includes('取袋') || dp.id.includes('data.自动上袋')
      );
      console.log('  相关数据点:', similarPoints);

      // 检查所有包含"自动上袋"的路径
      const allPaths = allDataPoints.map((dp) => dp.id).filter((id) => id.includes('自动上袋'));
      console.log('  所有包含"自动上袋"的路径:', allPaths);
    }
  });

  // 显示前20个数据点作为参考
  const allDataPoints = realtimeStore.dataPoints.value || [];
  console.log(
    '前20个数据点:',
    allDataPoints.slice(0, 20).map((dp) => ({
      id: dp.id,
      value: dp.value,
      sourceId: dp.sourceId
    }))
  );

  console.log('总数据点数量:', allDataPoints.length);
};

// 测试步骤条数组数据绑定
(window as any).$testStepsData = (stepsData?: any) => {
  const defaultStepsData = [
    { title: '开始', description: '流程开始', status: 'finish' },
    { title: '处理中', description: '正在处理数据', status: 'process' },
    { title: '完成', description: '流程完成', status: 'wait' }
  ];

  const testData = stepsData || defaultStepsData;
  console.log('测试步骤条数据:', testData);

  const message = {
    type: 'data',
    data: {
      steps: testData
    },
    source: 'steps_test',
    timestamp: Date.now()
  };

  realtimeStore.handleWebSocketMessage(message);

  setTimeout(() => {
    const dataPoint = realtimeStore.getDataPoint('data.steps');
    console.log('步骤条数据点状态:', dataPoint);
  }, 100);
};

// 测试表格数组数据绑定
(window as any).$testTableData = (tableData?: any) => {
  const defaultTableData = [
    { name: '张三', age: 25, city: '北京' },
    { name: '李四', age: 30, city: '上海' },
    { name: '王五', age: 28, city: '广州' }
  ];

  const testData = tableData || defaultTableData;
  console.log('测试表格数据:', testData);

  const message = {
    type: 'data',
    data: {
      tableData: testData
    },
    source: 'table_test',
    timestamp: Date.now()
  };

  realtimeStore.handleWebSocketMessage(message);

  setTimeout(() => {
    const dataPoint = realtimeStore.getDataPoint('data.tableData');
    console.log('表格数据点状态:', dataPoint);
  }, 100);
};

// 测试表格数据追加模式
(window as any).$testTableAppendData = (newData?: any) => {
  const defaultNewData = [
    { name: `新用户${Date.now()}`, age: Math.floor(Math.random() * 50) + 20, city: '深圳' }
  ];

  const testData = newData || defaultNewData;
  console.log('测试表格追加数据:', testData);

  const message = {
    type: 'data',
    data: {
      tableData: testData
    },
    source: 'table_append_test',
    timestamp: Date.now()
  };

  realtimeStore.handleWebSocketMessage(message);

  setTimeout(() => {
    const dataPoint = realtimeStore.getDataPoint('data.tableData');
    console.log('表格追加后数据点状态:', dataPoint);
  }, 100);
};

// 测试实时日志数据（追加模式）
(window as any).$testLogData = (logEntry?: any) => {
  const defaultLogEntry = [
    {
      time: new Date().toLocaleTimeString(),
      level: ['INFO', 'WARN', 'ERROR'][Math.floor(Math.random() * 3)],
      message: `系统消息 ${Date.now()}`,
      source: 'system'
    }
  ];

  const testData = logEntry || defaultLogEntry;
  console.log('测试日志数据:', testData);

  const message = {
    type: 'data',
    data: {
      logData: testData
    },
    source: 'log_test',
    timestamp: Date.now()
  };

  realtimeStore.handleWebSocketMessage(message);

  setTimeout(() => {
    const dataPoint = realtimeStore.getDataPoint('data.logData');
    console.log('日志数据点状态:', dataPoint);
  }, 100);
};

// 测试实时图表数据（追加模式）
(window as any).$testChartData = (chartPoint?: any) => {
  const now = new Date();
  const defaultChartPoint = [
    {
      time: now.toLocaleTimeString(),
      value: Math.floor(Math.random() * 100),
      timestamp: now.getTime()
    }
  ];

  const testData = chartPoint || defaultChartPoint;
  console.log('测试图表数据:', testData);

  const message = {
    type: 'data',
    data: {
      chartData: testData
    },
    source: 'chart_test',
    timestamp: Date.now()
  };

  realtimeStore.handleWebSocketMessage(message);

  setTimeout(() => {
    const dataPoint = realtimeStore.getDataPoint('data.chartData');
    console.log('图表数据点状态:', dataPoint);
  }, 100);
};

// 测试组件显示/隐藏控制
(window as any).$testVisibility = (visible: boolean = true) => {
  console.log(`测试组件显示/隐藏: ${visible}`);

  const message = {
    type: 'data',
    data: {
      componentVisible: visible
    },
    source: 'visibility_test',
    timestamp: Date.now()
  };

  realtimeStore.handleWebSocketMessage(message);

  setTimeout(() => {
    const dataPoint = realtimeStore.getDataPoint('data.componentVisible');
    console.log('组件可见性数据点状态:', dataPoint);
  }, 100);
};

// 测试设备状态控制（布尔值示例）
(window as any).$testDeviceStatus = (status: 'online' | 'offline' | 'error' = 'online') => {
  const statusMap = {
    online: true,
    offline: false,
    error: false
  };

  const visible = statusMap[status];
  console.log(`测试设备状态: ${status} -> 显示: ${visible}`);

  const message = {
    type: 'data',
    data: {
      deviceOnline: visible,
      deviceStatus: status
    },
    source: 'device_test',
    timestamp: Date.now()
  };

  realtimeStore.handleWebSocketMessage(message);

  setTimeout(() => {
    const dataPoint = realtimeStore.getDataPoint('data.deviceOnline');
    console.log('设备在线状态数据点:', dataPoint);
  }, 100);
};

// 测试报警状态控制
(window as any).$testAlarmStatus = (alarmActive: boolean = false) => {
  console.log(`测试报警状态: ${alarmActive ? '报警中' : '正常'}`);

  const message = {
    type: 'data',
    data: {
      alarmActive: alarmActive,
      systemNormal: !alarmActive
    },
    source: 'alarm_test',
    timestamp: Date.now()
  };

  realtimeStore.handleWebSocketMessage(message);

  setTimeout(() => {
    const alarmPoint = realtimeStore.getDataPoint('data.alarmActive');
    const normalPoint = realtimeStore.getDataPoint('data.systemNormal');
    console.log('报警状态数据点:', alarmPoint);
    console.log('系统正常数据点:', normalPoint);
  }, 100);
};

// 测试工业数据（温度、压力、流量等）
(window as any).$testIndustrialData = () => {
  const industrialData = {
    temperature: Math.random() * 100 + 20, // 20-120°C
    pressure: Math.random() * 10 + 1, // 1-11 bar
    flowRate: Math.random() * 500 + 100, // 100-600 L/min
    rpm: Math.random() * 3000 + 1000, // 1000-4000 RPM
    vibration: Math.random() * 5, // 0-5 mm/s
    efficiency: Math.random() * 0.3 + 0.7, // 70-100%
    status: Math.random() > 0.8 ? 'alarm' : Math.random() > 0.1 ? 'normal' : 'warning',
    lastUpdate: Date.now()
  };

  console.log('测试工业数据:', industrialData);

  const message = {
    type: 'data',
    data: industrialData,
    source: 'industrial_test',
    timestamp: Date.now()
  };

  realtimeStore.handleWebSocketMessage(message);

  setTimeout(() => {
    Object.keys(industrialData).forEach((key) => {
      const dataPoint = realtimeStore.getDataPoint(`data.${key}`);
      console.log(`${key} 数据点:`, dataPoint);
    });
  }, 100);
};

// 测试设备运行状态
(window as any).$testEquipmentStatus = (deviceId: string = 'device001') => {
  const statuses = ['running', 'stopped', 'maintenance', 'error', 'standby'];
  const currentStatus = statuses[Math.floor(Math.random() * statuses.length)];

  const equipmentData = {
    [`${deviceId}_status`]: currentStatus,
    [`${deviceId}_runtime`]: Math.floor(Math.random() * 10000), // 运行时间(小时)
    [`${deviceId}_energy`]: Math.random() * 1000, // 能耗(kWh)
    [`${deviceId}_count`]: Math.floor(Math.random() * 50000), // 生产计数
    [`${deviceId}_online`]: currentStatus !== 'maintenance' && currentStatus !== 'error'
  };

  console.log(`测试设备状态 [${deviceId}]:`, equipmentData);

  const message = {
    type: 'data',
    data: equipmentData,
    source: 'equipment_test',
    timestamp: Date.now()
  };

  realtimeStore.handleWebSocketMessage(message);

  setTimeout(() => {
    Object.keys(equipmentData).forEach((key) => {
      const dataPoint = realtimeStore.getDataPoint(`data.${key}`);
      console.log(`${key}:`, dataPoint?.value);
    });
  }, 100);
};

// 测试生产线数据
(window as any).$testProductionLine = () => {
  const productionData = {
    line_speed: Math.random() * 100 + 50, // 生产线速度 50-150 m/min
    output_count: Math.floor(Math.random() * 1000), // 产量计数
    defect_rate: Math.random() * 0.05, // 缺陷率 0-5%
    oee: Math.random() * 0.3 + 0.6, // OEE 60-90%
    shift: (Math.floor(Date.now() / (8 * 60 * 60 * 1000)) % 3) + 1, // 班次 1,2,3
    operators: Math.floor(Math.random() * 5) + 3, // 操作员数量 3-7
    quality_grade: ['A', 'B', 'C'][Math.floor(Math.random() * 3)]
  };

  console.log('测试生产线数据:', productionData);

  const message = {
    type: 'data',
    data: productionData,
    source: 'production_test',
    timestamp: Date.now()
  };

  realtimeStore.handleWebSocketMessage(message);

  setTimeout(() => {
    Object.keys(productionData).forEach((key) => {
      const dataPoint = realtimeStore.getDataPoint(`data.${key}`);
      console.log(`${key}:`, dataPoint?.value);
    });
  }, 100);
};

// 定时器测试 - 模拟实时数据更新
(window as any).$startRealTimeSimulation = (interval: number = 2000) => {
  if ((window as any)._realTimeTimer) {
    clearInterval((window as any)._realTimeTimer);
  }

  console.log(`开始实时数据模拟，更新间隔: ${interval}ms`);

  (window as any)._realTimeTimer = setInterval(() => {
    // 随机选择测试函数
    const testFunctions = [
      () => (window as any).$testIndustrialData(),
      () => (window as any).$testEquipmentStatus(),
      () => (window as any).$testProductionLine(),
      () => (window as any).$testTableAppendData()
    ];

    const randomTest = testFunctions[Math.floor(Math.random() * testFunctions.length)];
    randomTest();
  }, interval);

  return (window as any)._realTimeTimer;
};

// 停止实时数据模拟
(window as any).$stopRealTimeSimulation = () => {
  if ((window as any)._realTimeTimer) {
    clearInterval((window as any)._realTimeTimer);
    (window as any)._realTimeTimer = null;
    console.log('实时数据模拟已停止');
  }
};

// 显示数据绑定使用示例
(window as any).$showDataBindingExamples = () => {
  console.log('🎯 数据绑定配置示例：');

  console.log('\n📊 1. 进度条组件 - 绑定百分比：');
  console.log({
    enabled: true,
    dataPointId: 'data.efficiency',
    targetProperty: 'percentage',
    transform: 'percentage',
    updateInterval: 1000
  });

  console.log('\n📝 2. 文本组件 - 设备状态显示：');
  console.log({
    enabled: true,
    dataPointId: 'data.status',
    targetProperty: 'text',
    transform: 'custom',
    customTransform:
      'mapStatus(value, {running: "🟢运行中", stopped: "🔴已停止", maintenance: "🟡维护中", error: "🔴故障"})'
  });

  console.log('\n🌡️ 3. 文本组件 - 温度显示：');
  console.log({
    enabled: true,
    dataPointId: 'data.temperature',
    targetProperty: 'text',
    transform: 'custom',
    customTransform: 'formatNumber(value, 1) + "°C"'
  });

  console.log('\n🔄 4. Switch组件 - 设备开关：');
  console.log({
    enabled: true,
    dataPointId: 'data.device001_online',
    targetProperty: 'modelValue',
    transform: 'boolean',
    updateInterval: 2000
  });

  console.log('\n📋 5. 表格组件 - 用户列表：');
  console.log({
    enabled: true,
    dataPointId: 'data.tableData',
    targetProperty: 'data',
    transform: 'array',
    updateInterval: 5000
  });

  console.log('\n⚠️ 6. 文本组件 - 报警文本（显示/隐藏）：');
  console.log({
    enabled: true,
    dataPointId: 'data.alarmActive',
    targetProperty: 'text',
    transform: 'custom',
    customTransform: 'value ? "🚨 系统报警" : ""'
  });

  console.log('\n🎨 7. 文本组件 - 动态颜色：');
  console.log({
    enabled: true,
    dataPointId: 'data.temperature',
    targetProperty: 'color',
    transform: 'custom',
    customTransform: 'inRange(value, 20, 80) ? "#00ff00" : "#ff0000"'
  });

  console.log('\n⏰ 8. 文本组件 - 时间显示：');
  console.log({
    enabled: true,
    dataPointId: 'data.lastUpdate',
    targetProperty: 'text',
    transform: 'custom',
    customTransform: 'formatDateTime(value)'
  });

  console.log('\n📈 9. 进度条组件 - 百分比显示：');
  console.log({
    enabled: true,
    dataPointId: 'data.defect_rate',
    targetProperty: 'percentage',
    transform: 'custom',
    customTransform: 'Math.min(value * 100, 100)'
  });

  console.log('\n🎯 10. 文本组件 - 条件显示：');
  console.log({
    enabled: true,
    dataPointId: 'data.efficiency',
    targetProperty: 'text',
    transform: 'custom',
    customTransform: 'when(value > 0.9, "✅优秀", when(value > 0.7, "⚡良好", "⚠️需改进"))'
  });

  console.log('\n🚀 测试函数使用：');
  console.log('$testIndustrialData() - 工业数据');
  console.log('$testEquipmentStatus() - 设备状态');
  console.log('$testProductionLine() - 生产线数据');
  console.log('$startRealTimeSimulation() - 开始实时模拟');
  console.log('$stopRealTimeSimulation() - 停止实时模拟');
};

// 测试分段控制器数组数据绑定
(window as any).$testSegmentedData = (optionsData?: any) => {
  const defaultOptionsData = [
    { label: '日', value: 'day' },
    { label: '周', value: 'week' },
    { label: '月', value: 'month' },
    { label: '年', value: 'year' }
  ];

  const testData = optionsData || defaultOptionsData;
  console.log('测试分段控制器数据:', testData);

  const message = {
    type: 'data',
    data: {
      segmentedOptions: testData
    },
    source: 'segmented_test',
    timestamp: Date.now()
  };

  realtimeStore.handleWebSocketMessage(message);

  setTimeout(() => {
    const dataPoint = realtimeStore.getDataPoint('data.segmentedOptions');
    console.log('分段控制器数据点状态:', dataPoint);
  }, 100);
};

// 测试描述列表数据绑定
(window as any).$testDescriptionsData = (descriptionsData?: any) => {
  const defaultDescriptionsData = [
    { label: '用户名', value: 'admin' },
    { label: '手机号', value: '138****8888' },
    { label: '居住地', value: '北京市朝阳区' },
    { label: '备注', value: '无' }
  ];

  const testData = descriptionsData || defaultDescriptionsData;
  console.log('测试描述列表数据:', testData);

  const message = {
    type: 'data',
    data: {
      descriptionsData: testData
    },
    source: 'descriptions_test',
    timestamp: Date.now()
  };

  realtimeStore.handleWebSocketMessage(message);

  setTimeout(() => {
    const dataPoint = realtimeStore.getDataPoint('data.descriptionsData');
    console.log('描述列表数据点状态:', dataPoint);
  }, 100);
};

// 初始化实时数据Store
const realtimeStore = useRealtimeDataStore();

// 保存原始配置，用于拉伸模式的基准计算
let originalCanvasConfig = null;
let originalDoneJson = null;

onMounted(() => {
  if (mtPreviewProps.exportJson) {
    const { canvasCfg, gridCfg, importDoneJson } = useExportJsonToDoneJson(
      mtPreviewProps.exportJson
    );
    canvas_cfg.value = canvasCfg;
    grid_cfg.value = gridCfg;
    done_json.value = importDoneJson;

    // 保存原始配置
    originalCanvasConfig = JSON.parse(JSON.stringify(canvasCfg));
    originalDoneJson = JSON.parse(JSON.stringify(importDoneJson));

    // 初始化WebSocket连接
    initWebSocketConnections();

    // 初始化自适应配置
    if (canvas_cfg.value.adaptive_screen?.enabled) {
      // 延迟执行，确保DOM已渲染
      setTimeout(() => {
        calculatePreviewAdaptive();
      }, 100);
    }
  }

  // 监听窗口大小变化
  window.addEventListener('resize', onPreviewWindowResize);
});

onUnmounted(() => {
  // 组件卸载时清理WebSocket连接
  cleanupWebSocketConnections();

  // 清理resize监听器
  window.removeEventListener('resize', onPreviewWindowResize);
  if (previewResizeTimer) {
    clearTimeout(previewResizeTimer);
  }
});

// WebSocket连接管理
const initWebSocketConnections = () => {
  if (!canvas_cfg.value.dataSources || canvas_cfg.value.dataSources.length === 0) {
    return;
  }

  // 首先更新Pinia Store中的数据源配置（包含解析规则）
  realtimeStore.updateDataSourceConfigs(canvas_cfg.value.dataSources);

  // 设置全局消息处理器
  wsManager.setGlobalMessageHandler((message) => {
    // 将WebSocket消息传递给Pinia Store处理
    realtimeStore.handleWebSocketMessage(message);
  });

  // 更新WebSocket连接
  wsManager.updateDataSources(canvas_cfg.value.dataSources);
};

// 清理WebSocket连接
const cleanupWebSocketConnections = () => {
  wsManager.disconnectAll();
};

const setImportJson = (exportJson: IExportJson) => {
  const { canvasCfg, gridCfg, importDoneJson } = useExportJsonToDoneJson(exportJson);
  canvas_cfg.value = canvasCfg;
  grid_cfg.value = gridCfg;
  done_json.value = importDoneJson;

  // 保存原始配置
  originalCanvasConfig = JSON.parse(JSON.stringify(canvasCfg));
  originalDoneJson = JSON.parse(JSON.stringify(importDoneJson));

  // 初始化WebSocket连接
  initWebSocketConnections();

  // 检查并应用自适应配置
  if (canvas_cfg.value.adaptive_screen?.enabled) {
    setTimeout(() => {
      calculatePreviewAdaptive();
    }, 100);
  }

  return true;
};
defineExpose({
  setItemAttrByID,
  setImportJson,
  setItemAttrs
});
</script>
<style scoped>
.canvasArea {
  position: relative;
  transform: v-bind('`scale(${canvas_cfg.scale})`');
  transform-origin: v-bind(
    '`${canvas_cfg.transform_origin.x}px ${canvas_cfg.transform_origin.y}px`'
  );
  width: v-bind('canvas_cfg.width + "px"');
  height: v-bind('canvas_cfg.height + "px"');
  background-color: v-bind('canvas_cfg.color');
  background-image: v-bind('"url("+canvas_cfg.img+")"');
  left: v-bind('canvas_cfg.drag_offset.x + "px"');
  top: v-bind('canvas_cfg.drag_offset.y + "px"');
}

.debug-floating-buttons {
  position: fixed;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(8px);
  width: 60px;
}

.debug-floating-buttons .debug-btn {
  width: 36px !important;
  height: 36px !important;
  margin: 0 !important;
  padding: 0 !important;
  border-radius: 50% !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  flex-shrink: 0;
  position: relative !important;
}

.debug-floating-buttons .debug-icon {
  font-size: 14px;
  line-height: 1;
  display: block;
  text-align: center;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
